<template>
  <div class="h-full">
    <div class="main p-10 p-t-20 o-y-scroll scroll-touch">
      <div v-for="item in formatTypes" :key="item.id">
        <p class="fs-14 text-title">{{item.name}}</p>
        <div v-if="item.children.length"
          class="flex flex-wrap p-v-10">
          <div v-for="child in item.children" :key="child.id"
            @click="handleChooseType(child)"
            :class="{'active': chooseTypes.indexOf(child) > -1}"
            class="p-10 bg-block-grey fs-12 m-5 b-r-4 text-content flex a-center">
            <p>{{child.name}}</p>
            <van-icon
              v-show="chooseTypes.indexOf(child) > -1"
              class="fs-12 p-l-5"
              @click.capture.stop="handleRemoveType(child)"
              name="cross" />
          </div>
        </div>
        <div v-else class="fs-12 p-10 text-grey">
          暂无
        </div>
      </div>
    </div>
    <van-button
      @click="handleSubmit()"
      class="w-full"
      square
      type="danger">选好了</van-button>
  </div>
</template>

<script>
export default {
  props: {
    types: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    return {
      chooseTypes: []
    }
  },
  methods: {
    handleChooseType (type) {
      this.chooseTypes.push(type)
    },
    handleRemoveType (child) {
      let index = this.chooseTypes.indexOf(child)
      this.chooseTypes.splice(index, 1)
    },
    async handleSubmit () {
      if (!this.chooseTypes.length) {
        this.$toast('请选择商品分类')
        return
      }
      let data = this.chooseTypes.map(t => ({
        bid: '002',
        gid: t.id,
        gtype: t.type
      }))
      let { message } = await this.$api.post('/bsGt/set', data)
      this.$toast(message)
      this.$emit('close')
    },
    formatter (types) {
      types.pop()
      let originTypes = Array.from(types)
      let formatTypes = originTypes.filter(t => t.parentId === '0')
      formatTypes.forEach(t => {
        t.children = originTypes.filter(d => d.type === t.type && d.parentId !== '0')
      })
      return formatTypes
    }
  },
  computed: {
    formatTypes: {
      get () {
        return this.types && this.formatter(this.types)
      },
      set (val) {
        this.formatType = val
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: calc(100% - 44px);
}
.active {
  background: #fd4f51;
  color: #fff;
}
</style>
